package com.jxd.project.menu.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jxd.project.menu.dao.IMenuDao;
import com.jxd.project.menu.dto.MenuDTO;
import com.jxd.project.menu.dto.QueryMenuDTO;
import com.jxd.project.menu.model.Menu;
import com.jxd.project.menu.model.Role_Menu;
import com.jxd.project.menu.service.IMenuService;
import com.jxd.project.menu.service.IRole_MenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @ClassName PreMenuServiceImpl
 * @Description TODO
 * @Author 刘成
 * @Date 2025/10/11 9:46
 * @Version 1.0
 */
@Service
public class MenuServiceImpl extends ServiceImpl<IMenuDao,Menu> implements IMenuService{
    @Autowired
    private IMenuDao menuDao;
    @Autowired
    @Qualifier("role_MenuServiceImpl")
    private IRole_MenuService role_menuService;

    @Override
    public Map<String,Object> getWithQueryMenuDTO(QueryMenuDTO queryMenuDTO){
        IPage<Menu> page = new Page<>(queryMenuDTO.getCurrent(),queryMenuDTO.getSize());
        Map<String,Object> map = new HashMap<>();
        map.put("data",menuDao.selectWithFrontMenuId(page,queryMenuDTO.getFrontMenuId()));
        map.put("total",page.getTotal());
        return map;
    }

    @Override
    public List<Menu> getWithFrontMenus(){
        return menuDao.selectFrontMenus();
    }

    @Override
    @Transactional
    public boolean addOrEditMenu(MenuDTO menuDTO){
        Menu menu = menuDTO.getMenu();
        boolean flag2 = true;
        if (menu.getMenuId() != 0){
            flag2 = role_menuService.delWithMenuId(menu.getMenuId());
        }
        if (menu.getFrontMenu() == 0){
            menu.setMenuPath(null);
        }
        boolean flag1 = saveOrUpdate(menu);

        List<Role_Menu> role_menus = new ArrayList<>();
        for (int roleId : menuDTO.getBondRoles()) {
            Role_Menu role_menu = new Role_Menu();
            role_menu.setRoleId(roleId);
            role_menu.setMenuId(menu.getMenuId());
            role_menus.add(role_menu);
        }
        boolean flag3 = role_menuService.saveBatch(role_menus);
        return flag1 && flag2 && flag3;
    }
}
